package com.yeswater.algorithm.leetcode.hot100;

import com.yeswater.algorithm.leetcode.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Code102 {

    // 层序遍历
    public List<List<Integer>> levelOrder(TreeNode root) {

        List<List<Integer>> res = new ArrayList<>();

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        if (root == null) {
            return res;
        }

        int curCount = 1; // 记录第一层的节点数量
        int nextCount = 0; // 记录下一层的节点数量

        while (!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            while (curCount-->0){
                TreeNode node = queue.poll();
                list.add(node.val);
                if(node.left != null){
                    queue.offer(node.left);
                    nextCount++;
                }
                if(node.right != null){
                    queue.offer(node.right);
                    nextCount++;
                }
            }
            curCount = nextCount;
            nextCount = 0;
            res.add(list);
        }
        return res;

    }

}
